"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : SQL引擎插件
Case Name   : B类型数据库加载插件，多个用户并发连接进来，执行业务操作
Create At   : 2022.03.31
Owner       : z@wan005
Description :
    1.创建b库
    2.连接b库查询插件是否存在
    3.创建5个测试用户
    4.5个用户分别在兼容b库且有插件下给表插入大量数据
    5.修改线程池参数为on
    6.5个用户分别在兼容b库且有插件下删除表数据
    7.清理环境
Expect      :
     1.成功
     2.成功
     3.插件自动加载
     4.成功
     5.成功
     6.成功
     7.成功
History     :modified by z@wan005,2022.08.29，om数据库目前实现自动加载dolphin插件，
             因此删除用例中拷贝插件依赖文件步骤
"""
import os
import unittest

from testcase.utils.ComThread import ComThread
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class PluginTest021(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.common = Common()
        self.commonshpri = CommonSH('PrimaryDbUser')
        self.user_node = Node('PrimaryDbUser')
        self.us_name = "us_plugin0021"
        self.tb_name = "tb_plugin0021"
        self.db_name = "db_plugin0021"
        self.sql1 = f'-d {self.db_name} -U {self.us_name} ' \
                    f'-W {macro.PASSWD_INITIAL}'
        self.sql2 = f'-d {self.db_name} -U {self.us_name}_02 ' \
                    f'-W {macro.PASSWD_INITIAL}'
        self.sql3 = f'-d {self.db_name} -U {self.us_name}_03 ' \
                    f'-W {macro.PASSWD_INITIAL}'
        self.sql4 = f'-d {self.db_name} -U {self.us_name}_04 ' \
                    f'-W {macro.PASSWD_INITIAL}'
        self.sql5 = f'-d {self.db_name} -U {self.us_name}_05 ' \
                    f'-W {macro.PASSWD_INITIAL}'
        self.default_value = self.common.show_param('enable_thread_pool')
        sql_res = self.commonshpri.execut_db_sql('alter system set '
                                                 'enable_thread_pool to off;')
        self.log.info(sql_res)
        restart_msg = self.commonshpri.restart_db_cluster()
        self.log.info(restart_msg)

    def test_dolphin(self):
        text = '----step1:创建b库;expect:成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"create database {self.db_name} DBCOMPATIBILITY ='b';"
        self.log.info(sql_cmd)
        sql_res = self.commonshpri.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_res,
                      '执行失败' + text)

        text = '--step2:连接b库查询插件是否存在;expect:插件自动加载---'
        self.log.info(text)
        sql_cmd = "select extname from pg_extension where extname ='dolphin';"
        self.log.info(sql_cmd)
        sql_res = self.commonshpri.execut_db_sql(sql_cmd, dbname=self.db_name)
        self.log.info(sql_res)
        self.assertEqual('dolphin', sql_res.splitlines()[-2].strip(),
                         '执行失败' + text)

        text = '--step3:创建5个测试用户和表;expect:成功-----'
        self.log.info(text)
        cmd = f'''drop user if exists {self.us_name},{self.us_name}_02,\
        {self.us_name}_03,{self.us_name}_04,{self.us_name}_05;\
        create user {self.us_name} with sysadmin  password \
        '{macro.PASSWD_INITIAL}';
        create user {self.us_name}_02  with sysadmin password \
        '{macro.PASSWD_INITIAL}';
        create user {self.us_name}_03 with sysadmin  password \
        '{macro.PASSWD_INITIAL}';
        create user {self.us_name}_04 with sysadmin password \
        '{macro.PASSWD_INITIAL}';
        create user {self.us_name}_05 with sysadmin password \
        '{macro.PASSWD_INITIAL}';\
        drop table if  exists {self.tb_name};\
        create table {self.tb_name} \
        (id int, name text(10));'''
        result = self.commonshpri.execut_db_sql(cmd, dbname=self.db_name)
        self.log.info(result)
        self.assertTrue(
            result.count(self.constant.CREATE_ROLE_SUCCESS_MSG) == 5,
            '执行失败' + text)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, result,
                      '执行失败' + text)

        text = '---step4:5个用户分别在兼容b库下给表插入大量数据;expect:成功-----'
        self.log.info(text)
        create_cmd = f'''insert into {self.tb_name} values \
        (generate_series(1,1000000), 'col'|| generate_series(1,1000000));'''
        session_1 = ComThread(self.commonshpri.execut_db_sql,
                              args=(create_cmd, self.sql1))
        session_1.setDaemon(True)
        session_1.start()
        session_1.join(60)
        session_1_res = session_1.get_result()
        self.log.info(session_1_res)

        self.log.info('---用户2-----')
        session_2 = ComThread(self.commonshpri.execut_db_sql,
                              args=(create_cmd, self.sql2))
        session_2.setDaemon(True)
        session_2.start()
        session_2.join(60)
        session_2_res = session_2.get_result()
        self.log.info(session_2_res)

        self.log.info('---用户3-----')
        session_3 = ComThread(self.commonshpri.execut_db_sql,
                              args=(create_cmd, self.sql3))
        session_3.setDaemon(True)
        session_3.start()
        session_3.join(60)
        session_3_res = session_3.get_result()
        self.log.info(session_3_res)

        self.log.info('---用户4-----')
        session_4 = ComThread(self.commonshpri.execut_db_sql,
                              args=(create_cmd, self.sql4))
        session_4.setDaemon(True)
        session_4.start()
        session_4.join(60)
        session_4_res = session_4.get_result()
        self.log.info(session_4_res)

        self.log.info('---用户5-----')
        session_5 = ComThread(self.commonshpri.execut_db_sql,
                              args=(create_cmd, self.sql5))
        session_5.setDaemon(True)
        session_5.start()
        session_5.join(60)
        session_5_res = session_5.get_result()
        self.log.info(session_5_res)
        self.log.info('断言5个用户插入数据的结果')
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, session_1_res,
                      '执行失败' + text)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, session_2_res,
                      '执行失败' + text)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, session_3_res,
                      '执行失败' + text)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, session_4_res,
                      '执行失败' + text)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, session_5_res,
                      '执行失败' + text)

        text = '---step5:修改线程池参数为on;expect:成功-----'
        self.log.info(text)
        cmd = f'alter system set enable_thread_pool to on;'
        result = self.commonshpri.execut_db_sql(cmd)
        self.log.info(result)
        restart_msg = self.commonshpri.restart_db_cluster()
        self.log.info(restart_msg)

        text = '---step6:5个用户分别在兼容b库下删除表数据;expect:成功-----'
        self.log.info(text)
        create_cmd = f'''delete {self.tb_name};'''
        session_1 = ComThread(self.commonshpri.execut_db_sql,
                              args=(create_cmd, self.sql1))
        session_1.setDaemon(True)
        session_1.start()
        session_1.join(60)
        session_1_res = session_1.get_result()
        self.log.info(session_1_res)

        self.log.info('---用户2-----')
        session_2 = ComThread(self.commonshpri.execut_db_sql,
                              args=(create_cmd, self.sql2))
        session_2.setDaemon(True)
        session_2.start()
        session_2.join(60)
        session_2_res = session_2.get_result()
        self.log.info(session_2_res)

        self.log.info('---用户3-----')
        session_3 = ComThread(self.commonshpri.execut_db_sql,
                              args=(create_cmd, self.sql3))
        session_3.setDaemon(True)
        session_3.start()
        session_3.join(60)
        session_3_res = session_3.get_result()
        self.log.info(session_3_res)

        self.log.info('---用户4-----')
        session_4 = ComThread(self.commonshpri.execut_db_sql,
                              args=(create_cmd, self.sql4))
        session_4.setDaemon(True)
        session_4.start()
        session_4.join(60)
        session_4_res = session_4.get_result()
        self.log.info(session_4_res)

        self.log.info('---用户5-----')
        session_5 = ComThread(self.commonshpri.execut_db_sql,
                              args=(create_cmd, self.sql5))
        session_5.setDaemon(True)
        session_5.start()
        session_5.join(60)
        session_5_res = session_5.get_result()
        self.log.info(session_5_res)

        self.log.info('断言5个用户删除数据的结果')
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, session_1_res,
                      '执行失败' + text)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, session_2_res,
                      '执行失败' + text)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, session_3_res,
                      '执行失败' + text)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, session_4_res,
                      '执行失败' + text)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, session_5_res,
                      '执行失败' + text)

    def tearDown(self):
        text = '---step7:清理环境; expect:清理环境成功-----'
        self.log.info(text)
        self.log.info('删表')
        cmd = f"drop database if exists {self.db_name};"
        result = self.commonshpri.execut_db_sql(cmd)
        self.log.info(result)
        cmd = f"drop user if exists {self.us_name},{self.us_name}_02," \
              f"{self.us_name}_03,{self.us_name}_04,{self.us_name}," \
              f"{self.us_name}_05;"
        drop_res = self.commonshpri.execut_db_sql(cmd)
        self.log.info(drop_res)
        self.log.info('恢复参数默认值')
        self.commonshpri.execute_gsguc(
            "set", self.constant.GSGUC_SUCCESS_MSG,
            f"enable_thread_pool = {self.default_value}")
        self.commonshpri.restart_db_cluster()
        self.log.info('断言teardown成功')
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, result,
                      '执行失败' + text)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, drop_res,
                      '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
